package org.framework.lazy.cloud.network.heartbeat.client.netty.advanced;


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.client.AbstractHandleDistributeServicePermeateClientTransferTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.enums.MessageTypeEnums;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;


/**
 * 服务端处理客户端数据传输
 *
 * @see MessageTypeEnums#DISTRIBUTE_CLIENT_TRANSFER
 */
@Slf4j
public class ClientHandleChannelTransferTypeAdvancedHandleDistributeDistribute extends AbstractHandleDistributeServicePermeateClientTransferTypeAdvanced<NettyProxyMsg> {

    private final NettyClientProperties nettyClientProperties;

    public ClientHandleChannelTransferTypeAdvancedHandleDistributeDistribute(NettyClientProperties nettyClientProperties) {
        this.nettyClientProperties = nettyClientProperties;
    }

    /**
     * 处理当前数据
     *
     * @param channel       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    public void doHandler(Channel channel, NettyProxyMsg nettyProxyMsg) {
        log.debug("接收到服务端需要内网穿透的数据:{}" , nettyProxyMsg);
        String clientId = nettyClientProperties.getClientId();
        byte[] visitorPort = nettyProxyMsg.getVisitorPort();
        byte[] clientTargetIp = nettyProxyMsg.getClientTargetIp();
        byte[] clientTargetPort = nettyProxyMsg.getClientTargetPort();
        byte[] visitorId = nettyProxyMsg.getVisitorId();
        // 真实服务通道
//        Channel realChannel = NettyRealIdContext.getReal(new String(visitorId));
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
        if (nextChannel == null) {
            log.error("无法获取访客:{} 真实服务", new String(visitorId));
            return;
        }


        // 把数据转到真实服务
        ByteBuf buf = channel.config().getAllocator().buffer(nettyProxyMsg.getData().length);
        buf.writeBytes(nettyProxyMsg.getData());

        nextChannel.writeAndFlush(buf);

    }

}
